<template>
  <view class="upload-box" :class="{ 'upload-boxNew': onlyLook }">
    <view class="previewBox">
      <view
        @click.stop="chooseType"
        class="previewBoxItem"
        v-if="isShowUp(media)"
        :style="{ height: height + 'rpx', width: width + 'rpx' }"
      >
        <view class="size">
          <text class="f22 iconfont icon-camera"></text>
          <view class="up"
            >上传{{
              type == 'image' ? '图片' : type == 'video' ? '视频' : '视频/图片'
            }}
            <br />
            最多{{ limit - fileList.length }}张</view
          >
        </view>
      </view>
      <view
        class="previewBoxItem"
        v-for="(item, index) in fileList"
        :key="index"
        :style="{ height: height + 'rpx', width: width + 'rpx' }"
      >
        <image
          v-if="isVideo(item)"
          class="imgBox"
          :src="item + '?x-oss-process=video/snapshot,t_0,f_jpg'"
          @click.stop="previewVideo(item)"
          mode="aspectFill"
        ></image>
        <image
          v-else
          class="imgBox"
          :src="item"
          mode="aspectFill"
          @click.stop="previewClick(index)"
        ></image>
        <view @click.stop="deleteClick(index)" class="deleteBox">
          <u-icon name="trash" color="#FFFFFF" size="18"></u-icon>
        </view>
        <!-- 加入播放按键 -->
        <text
          class="font16 iconfontColor icon-video play_circle"
          v-if="mediaType == 2"
          @click.stop="previewVideo(item)"
        ></text>
      </view>
    </view>
    <view class="preview-full" v-if="previewVideoSrc != ''">
      <video
        :autoplay="true"
        :src="previewVideoSrc"
        :show-fullscreen-btn="false"
      >
        <cover-view class="preview-full-close" @click.stop="previewVideoClose">
          ×
        </cover-view>
      </video>
    </view>
    <u-action-sheet
      :actions="list"
      :show="show"
      @select="selectAction"
      @close="show = false"
      cancelText="取消"
    >
    </u-action-sheet>
    <u-loading-icon
      class="loading"
      :show="showLoading"
      text="上传中"
      textSize="18rpx"
    ></u-loading-icon>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
import dayjs from 'dayjs'
import { getUploadAccount } from '@/api/upload/upload.js'
import AliOss from '@/common/oss.js'

export default {
  props: {
    type: {
      type: String,
      default: 'all',
    },
    fileList: {
      type: Array,
      default: () => [],
    },
    onlyLook: {
      type: Boolean,
    },
    media: {
      type: Number,
      default: null,
    },
    mediaType: {
      type: Number,
      default: null,
    },
    height: {
      type: Number,
      default: 222,
    },
    width: {
      type: Number,
      default: 222,
    },
  },
  data() {
    return {
      time: '',
      // OSS STS数据
      limit: 9,
      ossData: {},
      show: false,
      list: [
        {
          name: '上传图片',
        },
        {
          name: '上传视频',
        },
      ],
      uploadList: [],
      uploadSizes: [],
      previewVideoSrc: '',
      showLoading: false,
    }
  },
  computed: {
    ...mapGetters(['token']),
  },
  watch: {
    fileList(n) {
      console.log(n, 'imglist变了====')
    },
  },
  mounted() {
    this.time = dayjs().format('YYYYMMDD')

    getUploadAccount().then(res => {
      this.ossData = res
    })
  },
  methods: {
    isShowUp(val) {
      console.log(val, 'media===============')
      if (val) {
        if (val == 1 && this.fileList.length < this.limit) {
          return true
        }
        if (val == 2 && this.fileList.length < 1) {
          return true
        }
      } else {
        return true
      }
    },
    isVideo(item) {
      let isPass = false
      if (!/.(gif|jpg|jpeg|png|gif|jpg|png)$/i.test(item)) {
        isPass = true
      }
      return isPass
    },
    // 预览图片
    previewClick(index) {
      let arr = []
      for (let item of this.fileList) {
        arr.push(item)
      }
      uni.previewImage({
        urls: arr,
        current: index,
      })
    },
    // 删除图片
    deleteClick(e) {
      this.$emit('del', e)
    },
    // 预览视频
    previewVideo(src) {
      this.previewVideoSrc = src
    },
    // 关闭预览
    previewVideoClose() {
      this.previewVideoSrc = ''
    },
    // 选择模式
    chooseType() {
      if (this.type == 'all') {
        // 有图片 不能再上传视频
        if (this.fileList.length) {
          this.uploadClick()
        } else {
          this.show = true
        }
      } else if (this.type == 'image') {
        this.uploadClick()
      } else if (this.type == 'video') {
        this.uploadVideo()
      }
    },
    // 选择
    selectAction(e) {
      switch (e.name) {
        case '上传图片':
          return this.uploadClick()
        case '上传视频':
          return this.uploadVideo()
        default:
          break
      }
    },
    // 选择图片 多图上传
    uploadClick() {
      this.$emit('media', 1)
      let limitNum = this.limit - this.fileList.length
      uni.chooseImage({
        count: limitNum,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: async res => {
          this.showLoading = true
          // 上传
          if (res.errMsg == 'chooseImage:ok') {
            // oss 配置信息
            let option = {
              savePath: `pet/pic/${this.time}`,
              AccessKeySecret: this.ossData.accessKeySecret,
              SecurityToken: this.ossData.securityToken,
              AccessKeyId: this.ossData.accessKeyId,
              bucket: this.ossData.buket,
              area: 'oss-cn-hangzhou',
            }
            // 图片多文件上传
            const files = res.tempFiles
            for (let i = 0; i < files.length; i++) {
              let filePath = files[i].path
              let size = parseInt(files[i].size / 1024)
              console.log(201, filePath)
              console.log(201, size)
              await this.asyncUpload(filePath, option, size)
            }
            this.$emit('success', this.uploadList)
            this.$emit('size', this.uploadSizes)
            this.showLoading = false
            this.uploadList = []
            console.log(this.limit, 'limit---')
          } else {
            uni.$u.toast('图片选择失败')
          }
        },
        fail: err => {
          console.log(err, 'err---------------------')
        },
      })
    },
    asyncUpload(filePath, option, size) {
      return new Promise((resolve, reject) => {
        AliOss.upload(filePath, option, res => {
          if (res) {
            this.uploadList.push(
              'https://' +
                option.bucket +
                '.' +
                option.area +
                '.aliyuncs.com/' +
                res
            )
            this.uploadSizes.push(size)
            resolve()
          } else {
            uni.$u.toast('上传失败，请稍后重试')
            this.showLoading = false
            reject()
          }
        })
      })
    },
    // 选择视频
    uploadVideo() {
      this.$emit('media', 2)
      uni.chooseVideo({
        sourceType: ['album', 'camera'],
        success: async res => {
          // 上传
          if (res.errMsg == 'chooseVideo:ok') {
            this.showLoading = true
            // oss 配置信息
            let option = {
              savePath: `pet/video/${this.time}`,
              AccessKeySecret: this.ossData.accessKeySecret,
              SecurityToken: this.ossData.securityToken,
              AccessKeyId: this.ossData.accessKeyId,
              bucket: this.ossData.buket,
              area: 'oss-cn-hangzhou',
            }
            let filePath = res.tempFilePath
            await this.asyncUpload(filePath, option)
            this.$emit('success', this.uploadList)
            console.log(this.limit, 'limit---')

            this.uploadList = []
            this.showLoading = false
          } else {
            uni.$u.toast('视频选择失败')
          }
        },
      })
    },
  },
}
</script>

<style lang="scss">
.f22 {
  font-size: 44rpx;
}

/* 上传图片 */
.size {
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.previewBox {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin: -0.6%;
}

.upload-box {
  position: relative;

  .loading {
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 999;
    transform: translate(-50%, -50%);
  }
}

.imgBox {
  position: relative;
  width: 100%;
  height: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.previewBoxItem {
  width: 32%;
  height: 32%;
  margin-right: 2%;
  margin-bottom: 2%;
  border-radius: 20rpx;
  position: relative;
  background: #f5f5f5;
  text-align: center;
  box-sizing: border-box;
  overflow: hidden;

  .imgBox {
    width: 100%;
    height: 100%;
  }

  .flex {
    justify-content: center;
  }

  .up {
    margin-top: 12rpx;
    font-size: 22rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 28rpx;
  }

  &:nth-child(3n) {
    margin-right: 0;
  }

  .play_circle {
    font-size: 32px;
    position: absolute;
    color: #fff;
    top: 50%;
    left: 50%;
    z-index: 999;
    transform: translate(-50%, -50%);
  }
}

/* 删除 */
.deleteBox {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  bottom: 20rpx;
  right: 20rpx;
  width: 44rpx;
  height: 44rpx;
  border-radius: 50%;
  background-color: rgba($color: #000000, $alpha: 0.4);
}

.preview-full {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  z-index: 1002;

  video {
    width: 100%;
    height: 100%;
    z-index: 1002;
  }

  &-close {
    position: fixed;
    right: 32rpx;
    top: 135rpx;
    width: 80rpx;
    height: 80rpx;
    line-height: 60rpx;
    text-align: center;
    z-index: 1003;
    color: #fff;
    font-size: 65rpx;
    font-weight: bold;
  }
}

.upload-boxNew {
  .previewBox {
    position: relative !important;
    right: -6rpx !important;
    .previewBoxItem {
      // margin-left: 15rpx !important;
      // margin-right: 0 !important;
      // margin-bottom: 0rpx !important;

      margin-right: 14rpx !important;
      margin-bottom: 14rpx !important;
    }

    .previewBoxItem:nth-child(1) {
      // background-color: pink !important;
      display: none !important;
    }

    .deleteBox {
      display: none !important;
    }
  }
}
</style>
